using AutoMapper;
using UwinEducation.Application.Common.Interfaces;
using UwinEducation.Application.Dtos;
using UwinEducation.Domain.Entities;
using UwinEducation.Domain.IRepositories;
using UwinEducation.Shared.Models;

namespace UwinEducation.Application.Services
{
    /// <summary>
    /// 学生缴费服务实现
    /// </summary>
    public class StudentPaymentService : IStudentPaymentService
    {
        private readonly IStudentPaymentRepository _studentPaymentRepository;
        private readonly IStudentRepository _studentRepository;
        private readonly ITeacherScheduleRepository _teacherScheduleRepository;
        private readonly IMapper _mapper;

        public StudentPaymentService(
            IStudentPaymentRepository studentPaymentRepository,
            IStudentRepository studentRepository,
            ITeacherScheduleRepository teacherScheduleRepository,
            IMapper mapper)
        {
            _studentPaymentRepository = studentPaymentRepository;
            _studentRepository = studentRepository;
            _teacherScheduleRepository = teacherScheduleRepository;
            _mapper = mapper;
        }

        /// <summary>
        /// 获取学生缴费分页列表
        /// </summary>
        public async Task<PagedResult<StudentPaymentDto>> GetPagedListAsync(StudentPaymentPageRequest pageRequest)
        {
            var result = await _studentPaymentRepository.GetPagedListAsync(pageRequest);
            return new PagedResult<StudentPaymentDto>
            {
                Total = result.Total,
                Items = _mapper.Map<List<StudentPaymentDto>>(result.Items)
            };
        }

        /// <summary>
        /// 获取学生缴费详情
        /// </summary>
        public async Task<StudentPaymentDto> GetByIdAsync(Guid id)
        {
            var payment = await _studentPaymentRepository.GetDetailsByIdAsync(id);
            if (payment == null)
            {
                throw new ArgumentException($"学生缴费记录不存在: {id}");
            }

            return _mapper.Map<StudentPaymentDto>(payment);
        }

        /// <summary>
        /// 创建学生缴费
        /// </summary>
        public async Task<StudentPaymentDto> CreateAsync(CreateStudentPaymentDto input)
        {
            var student = await _studentRepository.GetByIdAsync(input.StudentId);
            if (student == null)
            {
                throw new ArgumentException($"学生不存在: {input.StudentId}");
                return null; 
            }
            var teacherSchedule = await _teacherScheduleRepository.GetByIdAsync(input.TeacherScheduleGroupId);
            if (teacherSchedule == null)
            {
                throw new ArgumentException($"教师课表不存在: {input.TeacherScheduleGroupId}");
                return null;
            }
            var teacherScheduleGroup = await _studentPaymentRepository.GetByStudentAndTeacherScheduleAsync(input.StudentId, input.TeacherScheduleGroupId);
            if (teacherScheduleGroup != null)
            {
                throw new ArgumentException($"学生缴费记录已存在: {input.StudentId} - {input.TeacherScheduleGroupId}");
                return null;
            }

            var payment = StudentPayment.Create(
                input.StudentId,
                input.TeacherScheduleGroupId,
                input.TotalAmount,
                input.Amount,
                input.Remarks
            );


            await _studentPaymentRepository.AddAsync(payment);
            return _mapper.Map<StudentPaymentDto>(payment);
        }


        /// <summary>
        /// 更新学生缴费
        /// </summary>
        public async Task<StudentPaymentDto> UpdateAsync(UpdateStudentPaymentDto input)
        {
            var payment = await _studentPaymentRepository.GetByStudentAndTeacherScheduleAsync(input.StudentId, input.TeacherScheduleGroupId);
            if (payment == null)
            {
                throw new ArgumentException($"学生缴费记录不存在: {input.StudentId} - {input.TeacherScheduleGroupId}");
            }
            payment.PaidAmount = input.PaidAmount;
            payment.Remarks = input.Remarks;
            await _studentPaymentRepository.UpdateAsync(payment);
            return new StudentPaymentDto();
        }

        /// <summary>
        /// 删除学生缴费
        /// </summary>
        public async Task DeleteAsync(Guid id)
        {
            var payment = await _studentPaymentRepository.GetByIdAsync(id);
            if (payment == null)
            {
                throw new ArgumentException($"学生缴费记录不存在: {id}");
            }

            await _studentPaymentRepository.DeleteAsync(id);
        }

        /// <summary>
        /// 获取学生的所有缴费记录
        /// </summary>
        public async Task<List<StudentPaymentDto>> GetByStudentIdAsync(Guid studentId)
        {
            var payments = await _studentPaymentRepository.GetByStudentIdAsync(studentId);
            return _mapper.Map<List<StudentPaymentDto>>(payments);
        }

        /// <summary>
        /// 批量创建学生缴费
        /// </summary>
        public async Task<List<StudentPaymentDto>> CreateRangeAsync(List<CreateStudentPaymentDto> inputs)
        {
            //批量验证学生是否存在
            var _inputs = inputs.GroupBy(input => input.StudentId).Select(g => g.First()).ToList();

            var students = await _studentRepository.GetByIdsAsync(_inputs.Select(input => input.StudentId).ToList());
            if (students.Count != _inputs.Count)
            {
                throw new ArgumentException($"学生不存在: {inputs.Where(input => !students.Any(s => s.Id == input.StudentId)).Select(input => input.StudentId).ToList()}");
            }
            //根据StudentId和TeacherScheduleGroupId是否存在，如果存在则抛出异常
            var payments = await _studentPaymentRepository.GetByStudentIdsAndTeacherScheduleGroupIdsAsync(inputs.Select(input => input.StudentId).ToList(), inputs.Select(input => input.TeacherScheduleGroupId).ToList());
            
            //if (payments != null&& payments.Count>0)
            //{
            //    throw new ArgumentException($"学生缴费记录已存在: {inputs.Where(input => payments.Any(p => p.StudentId == input.StudentId && p.TeacherScheduleGroupId == input.TeacherScheduleGroupId)).Select(input => input.StudentId).ToList()}");

            //}

            //过滤掉payments中已存在的记录
            _inputs= _inputs.Where(input => !payments.Any(p => p.StudentId == input.StudentId && p.TeacherScheduleGroupId == input.TeacherScheduleGroupId)).ToList();

            //批量创建学生缴费
            payments = _inputs.Select(input => StudentPayment.Create(
                input.StudentId,
                input.TeacherScheduleGroupId,
                input.TotalAmount,
                input.Amount,
                input.Remarks
            )).ToList();

            await _studentPaymentRepository.AddRangeAsync(payments);
            return new List<StudentPaymentDto>();
        }

        /// <summary>
        /// 删除学生缴费记录
        /// </summary>
        public async Task DeleteByStudentIdAndTeacherScheduleIdAsync(Guid studentId, Guid teacherScheduleId)
        {
            await _studentPaymentRepository.DeleteByStudentIdAndTeacherScheduleIdAsync(studentId, teacherScheduleId);
        }

        





    }
}